<template>
<div>
  <view v-if="canIUse">
    <view class='header'>
      <van-icon name="contact" size="60px" />
      <!-- <van-icon name="chat" size="60px"/> -->
    </view>
    <view class='content'>
      <view>申请获取以下权限</view> <text>获得你的公开信息(昵称，头像等)</text>
    </view>
    <button class='bottom' type='primary' open-type="getUserInfo" lang="zh_CN" @getuserinfo="bindGetUserInfo">授权登录</button>
  </view>
  <view v-if="!canIUse">请升级微信版本</view>
</div>
</template>

<script>
import {
  mapState,
  mapActions,
  mapGetters
} from 'vuex'
import api from '@/utils/api'

export default {
  data() {
    return {
      canIUse: wx.canIUse('button.open-type.getUserInfo'),
      callbackUrl: '',
      brand_id: "",
      openid: "",
      is_ok: false,
      btn_text: '加载中...',
      scene:'',
      invitation_user_id:0
    }
  },
  computed: {
    ...mapGetters([
      'login_info',
      'user',
    ])
  },
  created() {
    console.log('get_user_info created')
  },
  // beforeMount() {
  mounted() {
    // console.log('mounted')
    var self = this
    // console.log('self.login_info',self.login_info)
    self.is_ok = false
    if (!self.login_info) {
      // debugger
      wx.showToast({
        title: '加载中',
        icon: 'loading',
        duration: 10000,
        mask: true
      })
      // console.log('loginInfo为空')
      // 未登陆过
      wx.login({
        success: async function(res) {
          console.log("wx.login success")
          if (res.code) {
            api.getOpenid({
              app_id: 'wx48cb88f0c7623bce',
              code: res.code
            }).then(result => {
              // console.log('getOpenid', result)
              // let openid = result.data.openid
              // let brand_id = result.data.brand_id
              if (result.code === 0) {
                wx.hideToast()
                self.is_ok = true
                self.$store.dispatch("login", result.data)
              }
            })
          } else {
            wx.showToast({
              title: '登录失败！',
              icon: 'none'
            })
            console.log('登录失败！' + res.errMsg)
          }
        }
      })
    }else{
      self.is_ok=true
    }
  },
  onLoad(options) {
    // thsl.log(options)
    console.log('get_user_info','options',options)
    this.callback_url = options.callback_url
    this.scene = options.scene
    this.invitation_user_id = options.invitation_user_id
    // console.log(this.scene)
  },

  methods: {
    log(tit,obj){
      console.log('get_user_info',title,obj)
    },
    bindGetUserInfo(e) {
      let self = this
      if (!self.is_ok) {
        wx.showToast({
          title: '加载中',
          icon: 'loading',
          duration: 10000,
          mask:true
        })
        return
      }
      console.log(e)
      api.wechatDecryptData({
        iv: e.target.iv,
        session_key: self.login_info.session_key,
        encrypted_data: e.target.encryptedData
      }).then(result => {
        console.log('wechatDecryptData result: ', result)
        if (result.code === 0) {
          let data = {
            brand_id: self.login_info.brand_id,
            open_id: self.login_info.openid,
            union_id: result.data.unionid,
             name:result.data.nick_name,
          }
          console.log('data', data)
          if (self.invitation_user_id > 0) {
            data.invitation_user_id = self.invitation_user_id
          }
          api.createWxUserV1(data).then(result => {
            console.log('createWxUser result: ', result)
            if (result.code === 0) {
              result.data.scene=self.scene
              self.$store.dispatch("setUser", result.data)
              console.log(self.callback_url)
              if (self.callback_url) {
                // 回调页面
                if (self.callback_url == '../user/index' || self.callback_url == '../home/index' || self.callback_url == '../order/index' || self.callback_url == '../activity/index') {
                  wx.switchTab({
                    url: self.callback_url,
                    success(res) {
                      console.log('success', res)
                    },
                    fail(res) {
                      console.log('fail', res)
                    }
                  })
                } else {

                  wx.redirectTo({
                    url: self.callback_url+"?scene="+self.scene,
                    success(res) {
                      console.log('success', res)
                    },
                    fail(res) {
                      console.log('fail', res)
                    }
                  })
                }

              } else {
                wx.navigateBack({
                  //返回上一页面或多级页面
                  delta: 1
                })
              }
            } else {
              console.log('createWxUser err:')
            }
          })
        }
      })
    }
  }
}
</script>

<style >
.header {
  margin: 90rpx 0 90rpx 50rpx;
  border-bottom: 1px solid #ccc;
  text-align: center;
  width: 650rpx;
  height: 300rpx;
  line-height: 450rpx;
}

.header image {
  width: 200rpx;
  height: 200rpx;
}

.content {
  margin-left: 50rpx;
  margin-bottom: 90rpx;
}

.content text {
  display: block;
  color: #9d9d9d;
  margin-top: 40rpx;
}

.bottom {
  border-radius: 80rpx;
  margin: 70rpx 50rpx;
  font-size: 35rpx;
}
</style>
